package com.star.robot.controller;

import com.star.robot.constant.Constant;
import com.star.robot.dto.*;
import com.star.robot.entity.Admin;
import com.star.robot.entity.JiaoFei;
import com.star.robot.entity.Project;
import com.star.robot.entity.Team;
import com.star.robot.enums.CompanyTypeEnum;
import com.star.robot.enums.ProjectClassEnum;
import com.star.robot.repository.JiaoFeiRepository;
import com.star.robot.specialficaition.TeamSpecial;
import com.star.robot.util.DtAreaUtil;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/jiaofei")
public class JiaoFeiController {

    @Autowired
    private TeamSpecial teamSpecial;


    @Autowired
    private DtAreaUtil dtAreaUtil;

    @Autowired
    private JiaoFeiRepository jiaoFeiRepository;

    @PersistenceContext //注入的是实体管理器,执行持久化操作
     EntityManager entityManager;

    @GetMapping(value = "/")
    public PageResultDto get(JiaoFeiReqDto requestDto){
        PageResultDto<JiaoFeiDto> results = new PageResultDto<>();
        if(requestDto.getPage() != null && requestDto.getLimit() != null) {
            //后端框架分页从0开始 前端框架从1开始
            if (requestDto.getPage() >= 1) {
                requestDto.setPage(requestDto.getPage() - 1);
            }
            Pageable page = new PageRequest(requestDto.getPage(), requestDto.getLimit());

            Page<JiaoFei> pageable = jiaoFeiRepository.findAll(new Specification() {
                @Override
                public Predicate toPredicate(Root root, CriteriaQuery cq, CriteriaBuilder cb) {


                    List<Predicate> conditions = new ArrayList<>();
                    //单位名称
                    if(!StringUtils.isEmpty(requestDto.getCompanyName())){
                        Predicate companyCond = cb.like(root.get("team").get("company").get("name") , "%"+requestDto.getCompanyName()+"%");
                        conditions.add(companyCond);
                    }
//                    //市
//                    if(requestDto.getCityId() != null){
//                        Predicate cityCondition = cb.equal(root.get("company").get("cityId")  , requestDto.getCityId());
//                        conditions.add(cityCondition);
//                    }

                    //单位性质
                    if(requestDto.getCompanyType() !=null){
                        CompanyTypeEnum companyType = null;
                        if(requestDto.getCompanyType().intValue() == 1){
                            companyType =  CompanyTypeEnum.XUEXIAO;
                        }else if(requestDto.getCompanyType().intValue() == 2){
                            companyType =  CompanyTypeEnum.JIGOU;
                        }else{
                            //默认学校
                            companyType =  CompanyTypeEnum.XUEXIAO;
                        }
                        Predicate companyTypeCond = cb.equal(root.get("team").get("company").get("companyType") ,companyType);
                        conditions.add(companyTypeCond);

                    }
                    //项目id
                    if(requestDto.getProjectId() != null){
                        Predicate projectCond = cb.equal(root.get("team").get("project").get("id") , requestDto.getProjectId());
                        conditions.add(projectCond);
                    }

                    //报名时间 => 队伍　新增时间
//                    if(!StringUtils.isEmpty(requestDto.getBaoMingDateStart())
//                            && !StringUtils.isEmpty(requestDto.getBaoMingDateEnd())){
//                        Predicate baoMingDateCond = cb.between(root.get("createTime") ,requestDto.getBaoMingDateStart() , requestDto.getBaoMingDateEnd());
//                        conditions.add(baoMingDateCond);
//                    }

                    //组别
                    if(requestDto.getGroupType() != null){
                        ProjectClassEnum groupTypeEnum = null;
                        if(requestDto.getGroupType() == 1){
                            groupTypeEnum = ProjectClassEnum.XIAOXUE;
                        }else if(requestDto.getGroupType() == 2){
                            groupTypeEnum = ProjectClassEnum.CHUZHONG;
                        }else if(requestDto.getGroupType() == 3){
                            groupTypeEnum = ProjectClassEnum.GAOZHONG;
                        }else{
                            //默认小学组
                            groupTypeEnum = ProjectClassEnum.XIAOXUE;
                        }
                        Predicate groupTypeCond = cb.equal(root.get("projectClassEnum") ,groupTypeEnum);
                        conditions.add(groupTypeCond);
                    }

                    Predicate[] pre = new Predicate[conditions.size()];

                    cq.where(conditions.toArray(pre));
                    return cq.getRestriction();
                }
            } , page);

            List<JiaoFeiDto> jiaoFeiDtos = new ArrayList<>();
            if(	!CollectionUtils.isEmpty(pageable.getContent()) ) {
                for(JiaoFei jiaofei :pageable.getContent()) {
                    String areaName = null;
                    String cityName = null;
                    String area = "";
                    if (!StringUtils.isEmpty(jiaofei.getTeam().getCompany().getProvinceId())) {
                        area += dtAreaUtil.getAreaName(Long.valueOf(jiaofei.getTeam().getCompany().getProvinceId()));
                    }
                    if (!StringUtils.isEmpty(jiaofei.getTeam().getCompany().getCityId())) {
                        if (area.length()>0) {
                            area += "-";
                        }
                        area += dtAreaUtil.getAreaName(Long.valueOf(jiaofei.getTeam().getCompany().getCityId()));
                    }
                    if (!StringUtils.isEmpty(jiaofei.getTeam().getCompany().getAreaId())) {
                        if (area.length()>0) {
                            area += "-";
                        }
                        area += dtAreaUtil.getAreaName(Long.valueOf(jiaofei.getTeam().getCompany().getAreaId()));
                    }

                    JiaoFeiDto jiaoFeiDto = new JiaoFeiDto();
                    jiaoFeiDto.setId(jiaofei.getId());
                    jiaoFeiDto.setCreateTime(jiaofei.getCreateTime());
                    jiaoFeiDto.setValue(jiaofei.getValue());
                    jiaoFeiDto.setStatus(jiaofei.getStatus());
                    jiaoFeiDto.setCompanyType(jiaofei.getTeam().getCompany().getCompanyType().getName());
                    jiaoFeiDto.setCompanyName(jiaofei.getTeam().getCompany().getName());
                    jiaoFeiDto.setTeamName(jiaofei.getTeam().getTeamName());
                    jiaoFeiDto.setTeamId(jiaofei.getTeam().getId());

                    jiaoFeiDtos.add(jiaoFeiDto);
                }
            }

            Page pagedTeamMembers = new PageImpl(jiaoFeiDtos , page ,pageable.getTotalElements() );
            results.setCount(pagedTeamMembers.getTotalElements());
            results.setData(pagedTeamMembers.getContent());

            return results;
        }
        return PageResultDto.builder().data(null).build();
    }

    @GetMapping(value = "/pay")
    public ResultDto pay(String ids,HttpServletRequest httpServletRequest){
        String[] id = ids.split(",");
        for (int i = 0;i<id.length;i++){
            JiaoFei jiaoFei = jiaoFeiRepository.findLongById(Long.parseLong(id[i]));
            jiaoFei.setStatus(true);
            jiaoFeiRepository.save(jiaoFei);
        }
        return ResultDto.builder().build();
    }
//    @GetMapping(value = "/wxpay")
//    public ResultDto wxpay(Map<String, String> reqData, HttpServletRequest httpServletRequest){
//
//    }


    @GetMapping(value = "/shiji")
    public PageResultDto jiaofeiShiji(JiaoFeiReqDto requestDto){
        PageResultDto<JiaoFeiDto> results = new PageResultDto<>();
        if(requestDto.getPage() != null && requestDto.getLimit() != null) {
            //后端框架分页从0开始 前端框架从1开始
            if (requestDto.getPage() >= 1) {
                requestDto.setPage(requestDto.getPage() - 1);
            }
            Pageable page = new PageRequest(requestDto.getPage(), requestDto.getLimit());

            Page<JiaoFei> pageable = jiaoFeiRepository.findAll(new Specification() {
                @Override
                public Predicate toPredicate(Root root, CriteriaQuery cq, CriteriaBuilder cb) {


                    List<Predicate> conditions = new ArrayList<>();
                    //单位名称
                    if(!StringUtils.isEmpty(requestDto.getCompanyName())){
                        Predicate companyCond = cb.like(root.get("team").get("company").get("name") , "%"+requestDto.getCompanyName()+"%");
                        conditions.add(companyCond);
                    }
//                    //市
//                    if(requestDto.getCityId() != null){
//                        Predicate cityCondition = cb.equal(root.get("company").get("cityId")  , requestDto.getCityId());
//                        conditions.add(cityCondition);
//                    }

                    //单位性质
                    if(requestDto.getCompanyType() !=null){
                        CompanyTypeEnum companyType = null;
                        if(requestDto.getCompanyType().intValue() == 1){
                            companyType =  CompanyTypeEnum.XUEXIAO;
                        }else if(requestDto.getCompanyType().intValue() == 2){
                            companyType =  CompanyTypeEnum.JIGOU;
                        }else{
                            //默认学校
                            companyType =  CompanyTypeEnum.XUEXIAO;
                        }
                        Predicate companyTypeCond = cb.equal(root.get("team").get("company").get("companyType") ,companyType);
                        conditions.add(companyTypeCond);

                    }
                    //项目id
                    if(requestDto.getProjectId() != null){
                        Predicate projectCond = cb.equal(root.get("team").get("project").get("id") , requestDto.getProjectId());
                        conditions.add(projectCond);
                    }

                    //报名时间 => 队伍　新增时间
//                    if(!StringUtils.isEmpty(requestDto.getBaoMingDateStart())
//                            && !StringUtils.isEmpty(requestDto.getBaoMingDateEnd())){
//                        Predicate baoMingDateCond = cb.between(root.get("createTime") ,requestDto.getBaoMingDateStart() , requestDto.getBaoMingDateEnd());
//                        conditions.add(baoMingDateCond);
//                    }

                    //组别
                    if(requestDto.getGroupType() != null){
                        ProjectClassEnum groupTypeEnum = null;
                        if(requestDto.getGroupType() == 1){
                            groupTypeEnum = ProjectClassEnum.XIAOXUE;
                        }else if(requestDto.getGroupType() == 2){
                            groupTypeEnum = ProjectClassEnum.CHUZHONG;
                        }else if(requestDto.getGroupType() == 3){
                            groupTypeEnum = ProjectClassEnum.GAOZHONG;
                        }else{
                            //默认小学组
                            groupTypeEnum = ProjectClassEnum.XIAOXUE;
                        }
                        Predicate groupTypeCond = cb.equal(root.get("projectClassEnum") ,groupTypeEnum);
                        conditions.add(groupTypeCond);
                    }

                    Predicate[] pre = new Predicate[conditions.size()];

                    cq.where(conditions.toArray(pre));
                    return cq.getRestriction();
                }
            } , page);

            List<JiaoFeiDto> jiaoFeiDtos = new ArrayList<>();
            if(	!CollectionUtils.isEmpty(pageable.getContent()) ) {
                for(JiaoFei jiaofei :pageable.getContent()) {
                    String areaName = null;
                    String cityName = null;
                    String area = "";
                    if (!StringUtils.isEmpty(jiaofei.getTeam().getCompany().getProvinceId())) {
                        area += dtAreaUtil.getAreaName(Long.valueOf(jiaofei.getTeam().getCompany().getProvinceId()));
                    }
                    if (!StringUtils.isEmpty(jiaofei.getTeam().getCompany().getCityId())) {
                        if (area.length()>0) {
                            area += "-";
                        }
                        area += dtAreaUtil.getAreaName(Long.valueOf(jiaofei.getTeam().getCompany().getCityId()));
                    }
                    if (!StringUtils.isEmpty(jiaofei.getTeam().getCompany().getAreaId())) {
                        if (area.length()>0) {
                            area += "-";
                        }
                        area += dtAreaUtil.getAreaName(Long.valueOf(jiaofei.getTeam().getCompany().getAreaId()));
                    }

                    JiaoFeiDto jiaoFeiDto = new JiaoFeiDto();
                    jiaoFeiDto.setId(jiaofei.getId());
                    jiaoFeiDto.setCreateTime(jiaofei.getCreateTime());
                    jiaoFeiDto.setValue(jiaofei.getValue());
                    jiaoFeiDto.setStatus(jiaofei.getStatus());
                    jiaoFeiDto.setCompanyType(jiaofei.getTeam().getCompany().getCompanyType().getName());
                    jiaoFeiDto.setCompanyName(jiaofei.getTeam().getCompany().getName());
                    jiaoFeiDto.setTeamName(jiaofei.getTeam().getTeamName());
                    jiaoFeiDto.setTeamId(jiaofei.getTeam().getId());

                    jiaoFeiDtos.add(jiaoFeiDto);
                }
            }

            Page pagedTeamMembers = new PageImpl(jiaoFeiDtos , page ,pageable.getTotalElements() );
            results.setCount(pagedTeamMembers.getTotalElements());
            results.setData(pagedTeamMembers.getContent());

            return results;
        }
        return PageResultDto.builder().data(null).build();
    }

    @GetMapping(value = "/applyEd")
    public PageResultDto applyEd(JiaoFeiReqDto requestDto,HttpServletRequest request){
        PageResultDto result = new PageResultDto();
        int page = requestDto.getPage();
        int limit = requestDto.getLimit();
        StringBuffer sb = new StringBuffer("SELECT\n" +
                "\ta.id,\n" +
                "\tb.`name` companyName,\n" +
                "\tc.area_name areaName,\n" +
                "\tb.company_type companyType,\n" +
                "\ta.team_name teamName,\n" +
                "\ta.create_time createTime,\n" +
                "\tCOUNT(d.id) count,\n" +
                "\te.`name` projectName,\n" +
                "\te.project_level_enum projectType\n" +
                "FROM\n" +
                "\tteam a\n" +
                "LEFT JOIN company b ON a.company_id = b.id\n" +
                "LEFT JOIN dt_area c ON b.city_id = c.id\n" +
                "LEFT JOIN team_member d ON d.team_id = a.id\n" +
                "LEFT JOIN project e ON a.project_id = e.id\n" +
                "LEFT JOIN project_class_enum f ON f.project_id = e.id\n"+
                "WHERE\n" +
                "\ta.confirm_status = '1'\n" +
                "AND a.template_id IS NULL\n" );
        StringBuffer sb1 = new StringBuffer("SELECT count(*)\n" +
                "FROM\n" +
                "\tteam a\n" +
                "LEFT JOIN company b ON a.company_id = b.id\n" +
                "LEFT JOIN dt_area c ON b.city_id = c.id\n" +
                "LEFT JOIN project e ON a.project_id = e.id\n" +
                "LEFT JOIN project_class_enum f ON f.project_id = e.id\n"+
                "WHERE\n" +
                "\ta.confirm_status = '1'\n" +
                "AND a.template_id IS NULL" );
        Admin admin = (Admin) request.getSession().getAttribute(Constant.CURRENTADMIN);
        if(admin.getCityId() != null && !"".equals(admin.getCityId())){
            sb.append(" and b.city_id = "+admin.getCityId());
            sb1.append(" and b.city_id = "+admin.getCityId());
        }
        if(requestDto.getCompanyName() != null && !"".equals(requestDto.getCompanyName())){
            sb.append(" and b.name = '" +requestDto.getCompanyName()+"'" );
            sb1.append(" and b.name = '" +requestDto.getCompanyName()+"'" );
        }
        if (requestDto.getCompanyType() != null && !"-1".equals(requestDto.getCompanyType()+"")){
            sb.append(" and b.company_type = '" + requestDto.getCompanyType()+"'");
            sb1.append(" and b.company_type = '" + requestDto.getCompanyType()+"'");
        }
        if (requestDto.getProjectName() != null && !"".equals(requestDto.getProjectName())){
            sb.append(" and e.name = '" + requestDto.getProjectName()+"'");
            sb1.append(" and e.name = '" + requestDto.getProjectName()+"'");
        }
        if (requestDto.getGroupType() != null && !"-1".equals(requestDto.getGroupType()+"")){
            sb.append(" and f.code = '" + requestDto.getGroupType()+"'");
            sb1.append(" and f.code = '" + requestDto.getGroupType()+"'");
        }
        if(requestDto.getStartTime() != null && !"".equals(requestDto.getStartTime())){
            sb.append(" and a.create_time >= '"+ requestDto.getStartTime()+"'");
            sb1.append(" and a.create_time >= '"+ requestDto.getStartTime()+"'");
        }
        if(requestDto.getEndTime() != null && !"".equals(requestDto.getEndTime())){
            sb.append(" and a.create_time <= '"+ requestDto.getEndTime()+"'");
            sb1.append(" and a.create_time <= '"+ requestDto.getEndTime()+"'");
        }
        sb.append(" ORDER BY a.create_time DESC limit " +(page-1)*limit+","+limit);
//        Query query = entityManager.createNativeQuery(sb.toString(),Map.class);
        Query query = entityManager.createNativeQuery(sb.toString());
        query.unwrap(org.hibernate.SQLQuery.class)
                .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map<String,Object>> list = query.getResultList();
        Query query1 = entityManager.createNativeQuery(sb1.toString());
        Long count = ((BigInteger)query1.getSingleResult()).longValue();
        if(list.get(0).get("id") != null) {
            result.setData(list);
        }
        result.setCount(count);
        return result;
    }

}
